package com.ai.deepseekspring.interceptor;



import com.ai.deepseekspring.Anno.Auth;
import com.ai.deepseekspring.utils.TokenUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;



public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.getBean() instanceof BasicErrorController) {
                return true;
            }

            Auth auth = handlerMethod.getMethod().getAnnotation(Auth.class);
            System.out.println("Auth 注解: " + auth);
            if (auth != null) {
                System.out.println("Auth.require: " + auth.require());
            }
            if (auth != null && auth.require()) {

                String token = request.getHeader("token");
                if (StringUtils.isNotBlank(token)) {
                    if (TokenUtil.verifyToken(token)) { // 校验 token 是否正确
                        return true;
                    } else {
                        request.getRequestDispatcher("/error/tokenError").forward(request, response); // 这里你也可以直接抛出自定义异常，然后在全局异常处理器中处理
                    }
                } else {
                    request.getRequestDispatcher("/error/token").forward(request, response); // 这里你也可以直接抛出自定义异常，然后在全局异常处理器中处理
                }
            } else {
                return true;
            }
        } else {

            return true;
        }
        return false;

    }

}